package com.waterworld.watch.common.application;

import android.annotation.SuppressLint;
import android.app.ActivityManager;
import android.app.Application;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.support.multidex.MultiDex;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;

import com.alibaba.sdk.android.push.CloudPushService;
import com.alibaba.sdk.android.push.CommonCallback;
import com.alibaba.sdk.android.push.noonesdk.PushServiceFactory;
import com.kct.sdk.KCSdk;
import com.kct.sdk.listen.KCEventListen;
import com.kct.sdk.util.KCLog;
import com.squareup.leakcanary.LeakCanary;
import com.squareup.leakcanary.LeakCanary;
import com.waterworld.watch.BuildConfig;
import com.waterworld.watch.call.call.VideoCallActivity;
import com.waterworld.watch.call.utils.UIAction;
import com.waterworld.watch.common.service.OverallService;
import com.waterworld.watch.common.util.LauncherCrashHandler;

import java.util.Iterator;
import java.util.Timer;
import java.util.TimerTask;

import static com.kct.sdk.KCBase.CALL_ALERT;
import static com.kct.sdk.KCBase.CALL_ANETWORK;
import static com.kct.sdk.KCBase.CALL_ANSWER;
import static com.kct.sdk.KCBase.CALL_AUDIO_MODE;
import static com.kct.sdk.KCBase.CALL_HANDUP;
import static com.kct.sdk.KCBase.CALL_INCOME;
import static com.kct.sdk.KCBase.CALL_OUTFAIL;
import static com.kct.sdk.KCBase.CALL_VNETWORK;
import static com.kct.sdk.KCBase.TCP_CONNECT;
import static com.kct.sdk.KCBase.TCP_DISCONNECT;

public class MyApplication extends Application implements KCEventListen{

    private static MyApplication instance = null;
    private static Context mContext;
    private OverallService mService = null;
    private static final String TAG = MyApplication.class.getSimpleName();
    public static String deviceId;


    // 通话计时
    private int second = 0;
    private int minute = 0;
    private int hour = 0;
    private Timer timer = null;
    // TCP连接状态
    public boolean bConnect = false;
    // 是否重连标记
    public boolean bReCon = false;

    @Override
    public void onCreate() {
        super.onCreate();
        instance = this;
        mContext = getApplicationContext();
        //LauncherCrashHandler.getInstance().init(this);
        if(isAppProcess()){

            KCSdk.getInstance().Init(this);
            KCSdk.getInstance().AddCallBack(this);
            bindService();   //绑定全局服务
            //内存泄漏检测
            //initLeakCanary();
        }
        initCloudChannel(mContext);
    }

    private void initCloudChannel(Context applicationContext) {
        PushServiceFactory.init(applicationContext);
        CloudPushService pushService = PushServiceFactory.getCloudPushService();
        deviceId = pushService.getDeviceId();
        pushService.register(applicationContext, new CommonCallback() {
            @Override
            public void onSuccess(String response) {
                Log.e(TAG, "init cloudchannel success");
            }
            @Override
            public void onFailed(String errorCode, String errorMessage) {
                Log.e(TAG, "init cloudchannel failed -- errorcode:" + errorCode + " -- errorMessage:" + errorMessage);
            }
        });
    }


    /**
     * 得到Application的实例
     */
    public static MyApplication getInstance(){
        return instance;
    }

    public static Context getContext() {
        return mContext;
    }

    private void bindService(){
        Intent intent = new Intent(mContext, OverallService.class);
        bindService(intent,conn,BIND_AUTO_CREATE);
    }

    public OverallService getService() {
        return mService;
    }

    private ServiceConnection conn = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            OverallService.LocalBinder binder = (OverallService.LocalBinder) service;
            mService = binder.getService();
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            mService = null;
        }
    };

    private String SessionID = "";

    public void setSessionID(String SessionID){
        this.SessionID = SessionID;
    }

    public String getSessionID() {
        return SessionID;
    }

    @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);
        //MultiDex.install(base);
    }

    /**
     * 判断该进程是否是app进程
     * @return
     */
    public boolean isAppProcess() {
        String processName = getMProcessName();
        if (processName == null || !processName.equalsIgnoreCase(this.getPackageName())) {
            return false;
        }else {
            return true;
        }
    }

    /**
     * 获取运行该方法的进程的进程名
     * @return 进程名称
     */
    public String getMProcessName() {
        int processId = android.os.Process.myPid();
        String processName = null;
        ActivityManager manager = (ActivityManager) getApplicationContext().getSystemService(Context.ACTIVITY_SERVICE);
        Iterator iterator = manager.getRunningAppProcesses().iterator();
        while (iterator.hasNext()) {
            ActivityManager.RunningAppProcessInfo processInfo = (ActivityManager.RunningAppProcessInfo) (iterator.next());
            try {
                if (processInfo.pid == processId) {
                    processName = processInfo.processName;
                    return processName;
                }
            } catch (Exception e) {
            }
        }
        return processName;
    }

    private void initLeakCanary() {
        if (LeakCanary.isInAnalyzerProcess(this)) {
            return;
        }
        LeakCanary.install(this);
    }

    @Override
    public void onTerminate() {
        KCSdk.getInstance().RemoveCallBack(this);
        KCSdk.getInstance().Free();
        super.onTerminate();
    }

    @SuppressLint("HandlerLeak")
    public Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == 1000) {
                if (bReCon) {
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            KCSdk.getInstance().TcpConnect();
                        }
                    }).start();
                }
            }
            if (msg.what == 1001) {
                if (bReCon) {
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            KCSdk.getInstance().NextTcpConnect();
                        }
                    }).start();
                }
            }
            super.handleMessage(msg);
        }
    };

    // 通话走时
    public void startCallTimer() {
        stopCallTimer();
        if (timer == null) {
            timer = new Timer();
        }
        second = 0; //秒
        minute = 0; //分
        hour = 0;   //时
        timer.scheduleAtFixedRate(new TimerTask() {
            @Override
            public void run() {
                StringBuffer timer = new StringBuffer();
                second++;
                if (second >= 60) {
                    minute++;
                    second = 0;
                }
                if (minute >= 60) {
                    hour++;
                    minute = 0;
                }
                if (hour != 0) {
                    if (hour < 10) {
                        timer.append(0);
                    }
                    timer.append(hour);
                    timer.append(":");
                }
                if (minute < 10) {
                    timer.append(0);
                }
                timer.append(minute);
                timer.append(":");
                if (second < 10) {
                    timer.append(0);
                }
                timer.append(second);
                // 发送给UI显示
                Intent mIntent = new Intent(UIAction.ACTION_CALL_TIME);
                mIntent.putExtra(UIAction.CALL_TIME_TOTAL, hour * 3600 + minute * 60 + second);
                mIntent.putExtra(UIAction.CALL_TIME_STRING, timer.toString());
                sendBroadcast(mIntent);
            }
        }, 0, 1000);
    }

    public void stopCallTimer() {
        if (timer != null) {
            timer.cancel();
            timer = null;
        }
    }

    @Override
    public void CallBackFunc(int i, int i1, int i2, String s) {
        if (i == TCP_CONNECT) {
            KCLog.e("TCP_CONNECT");
            Intent mIntent = new Intent(UIAction.ACTION_LOGIN_RESPONSE);
            mIntent.putExtra(UIAction.RESULT_KEY, 0);
            sendBroadcast(mIntent);
            bConnect = true;
        }
        if (i == TCP_DISCONNECT) {
            KCLog.e("TCP_DISCONNECT code = " + i1 + ", param = " + i2);
            bConnect = false;
            if (i1 == 0) {
                if (i2 == 0) {
                    // 正常退出
                }
                if (i2 == 1) {
                    // TCP连接失败,换一个服务器登录
                    mHandler.removeMessages(1001);
                    mHandler.sendEmptyMessageDelayed(1001, 500);
                }
                if (i2 == 2) {
                    // TCP心跳失败,重连
                    mHandler.removeMessages(1000);
                    mHandler.sendEmptyMessageDelayed(1000, 500);
                }
                if (i2 == 3) {
                    // 读失败，网络断开
                    //KCSdk.getInstance().ChangeICE(ICE_RTPP); // 0:P2P 1:RTPP
                    mHandler.removeMessages(1000);
                    mHandler.sendEmptyMessageDelayed(1000, 500);
                }
                if (i2 == 4) {
                    // 写失败，网络断开
                    //KCSdk.getInstance().ChangeICE(ICE_RTPP); // 0:P2P 1:RTPP
                    mHandler.removeMessages(1000);
                    mHandler.sendEmptyMessageDelayed(1000, 500);
                }
                if (i2 == 5) {
                    // SSID过期，需要退出从新登录
                    Intent mIntent = new Intent(UIAction.ACTION_LOGIN_RESPONSE);
                    mIntent.putExtra(UIAction.RESULT_KEY, 100);
                    sendBroadcast(mIntent);
                }
                if (i2 == 6) {
                    // 已经被别人登录
                    Intent mIntent = new Intent(UIAction.ACTION_LOGIN_RESPONSE);
                    mIntent.putExtra(UIAction.RESULT_KEY, 101);
                    sendBroadcast(mIntent);
                }
                if (i2 == 7) {
                    // 强制下线了
                    Intent mIntent = new Intent(UIAction.ACTION_LOGIN_RESPONSE);
                    mIntent.putExtra(UIAction.RESULT_KEY, 102);
                    sendBroadcast(mIntent);
                }
            } else if (i1 == 1) {
                // 账号认证失败
                Intent mIntent = new Intent(UIAction.ACTION_LOGIN_RESPONSE);
                mIntent.putExtra(UIAction.RESULT_KEY, 1);
                sendBroadcast(mIntent);
            } else if (i1 == 2) {
                // 获取服务器地址失败
                Intent mIntent = new Intent(UIAction.ACTION_LOGIN_RESPONSE);
                mIntent.putExtra(UIAction.RESULT_KEY, 1);
                sendBroadcast(mIntent);
            } else if (i1 == 3) {
                // 获取信令服务器地址失败
                Intent mIntent = new Intent(UIAction.ACTION_LOGIN_RESPONSE);
                mIntent.putExtra(UIAction.RESULT_KEY, 1);
                sendBroadcast(mIntent);
            }
        }
        if (i == CALL_OUTFAIL) {
            KCLog.e("CALL_OUTFAIL");
            // 停止计时
            stopCallTimer();
            // 发送报告
            Intent mIntent = new Intent(UIAction.ACTION_DIAL_STATE);
            mIntent.putExtra(UIAction.DAIL_STATE, s);
            sendBroadcast(mIntent);
        }
        if (i == CALL_INCOME) {
            KCLog.e("CALL_INCOME");
            Intent intent = new Intent();
            intent.setClass(this, VideoCallActivity.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            intent.putExtra("phoneNumber", s);
            intent.putExtra("inCall", true);
            startActivity(intent);
        }
        if (i == CALL_ANSWER) {
            KCLog.e("CALL_ANSWER");
            Intent mIntent = new Intent(UIAction.ACTION_ANSWER);
            sendBroadcast(mIntent);
            // 启动计时
            startCallTimer();
        }
        if (i == CALL_ALERT) {
            KCLog.e("CALL_ALERT");
            Intent mIntent = new Intent(UIAction.ACTION_DIAL_STATE);
            mIntent.putExtra(UIAction.DAIL_STATE_ALERT, 1);
            sendBroadcast(mIntent);
        }
        if (i == CALL_HANDUP) {
            KCLog.e("CALL_HANDUP");
            // 停止计时
            stopCallTimer();
            // 发送报告
            Intent mIntent = new Intent(UIAction.ACTION_DIAL_STATE);
            mIntent.putExtra(UIAction.DAIL_STATE, s);
            sendBroadcast(mIntent);
        }
        if (i == CALL_ANETWORK) {
            //Intent mIntent = new Intent(UIAction.ACTION_NETWORK_STATE);
            //mIntent.putExtra(UIAction.NETWORK_STATE, i);
            //sendBroadcast(mIntent);
        }
        if (i == CALL_VNETWORK) {
            Intent mIntent = new Intent(UIAction.ACTION_NETWORK_STATE);
            mIntent.putExtra(UIAction.NETWORK_STATE, i);
            mIntent.putExtra(UIAction.NETWORK_STRING, s);
            sendBroadcast(mIntent);
        }
        if (i == CALL_AUDIO_MODE) {
            Intent mIntent = new Intent(UIAction.ACTION_AUDIO_MODE);
            sendBroadcast(mIntent);
        }
    }
}
